﻿using Pay.Dal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pay.Model.Dto;
using Pay.Model.Interfaces;
using Dapper;
using Pay.Dapper;
using Pay.Model;
using Dapper.Contrib.Extensions;
namespace Pay.DalImplement
{
    public class QRCodeDalImplement : IQRCodeDal
    {
        /// <summary>
        ///根据ID获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<QRCodeInfo> GetById(long id)
        {

            using (var conn = ConnectionFactory.GetReadConnection())
            {
                string sql = "SELECT q.Id,q.AliAccountId,q.Amount,q.Address,q.NewAddress,q.NewImageName,q.QRcodeUrl,q.Description,q.CreateTime from qrcode_info q where q.id=@id";

                return await conn.QueryFirstOrDefaultAsync<QRCodeInfo>(sql, new { id = id });
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<bool> Delete(QRCodeInfo model)
        {
            using (var conn = ConnectionFactory.GetReadConnection())
            {
                return await conn.DeleteAsync<QRCodeInfo>(model);
            }
        }

        public async Task<IPagedOutput<QRCodeOutPut>> GetPage(string searchAccount, DateTime? timeBegin = null, DateTime? timeEnd = null, int offset = 10, int rows = 1)
        {
            StringBuilder sb = new StringBuilder("SELECT q.Id,q.AliAccountId,q.Amount,q.Address,q.NewAddress,q.NewImageName,q.QRcodeUrl,q.Description,q.CreateTime,a.AccountName from qrcode_info q inner join aliaccount_info a on a.id=q.AliAccountId where 1=1");
            DynamicParameters param = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(searchAccount))
            {
                sb.Append(" and  a.AccountName like '%'+@searchAccount+'%'");
                param.Add("@searchAccount", searchAccount);
            }
            if (timeBegin.HasValue && timeEnd.HasValue)
            {
                sb.Append(" and  q.createtime >=@timeBegin and q.createTime <=@timeEnd");
                param.Add("@timeBegin", timeBegin.Value);
                param.Add("@timeEnd", timeEnd.Value);

            }

            using (var conn = ConnectionFactory.GetReadConnection())
            {
                return await conn.PagedByAsync<QRCodeOutPut>(sb, param, offset, rows, "createTime", false);
            }
        }
    }
}
